package com.phiture.erp.stock.web.controller.admin;

import cn.hutool.core.collection.CollUtil;
import cn.iocoder.yudao.framework.apilog.core.annotation.ApiAccessLog;
import cn.iocoder.yudao.framework.common.pojo.CommonResult;
import cn.iocoder.yudao.framework.common.pojo.PageParam;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.util.collection.MapUtils;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;
import cn.iocoder.yudao.framework.excel.core.util.ExcelUtils;
import com.phiture.erp.basic.api.pojo.resp.ErpMaterialInfoResp;
import com.phiture.erp.basic.api.service.ErpMaterialApi;
import com.phiture.erp.stock.core.pojo.dto.ErpStockPageReqDTO;
import com.phiture.erp.stock.core.pojo.vo.ErpStockRespVO;
import com.phiture.erp.stock.core.service.ErpStockService;
import com.phiture.erp.stock.core.service.ErpWarehouseService;
import com.phiture.erp.stock.dal.entity.ErpStockDO;
import com.phiture.erp.stock.dal.entity.ErpWarehouseDO;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Parameters;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.List;
import java.util.Map;

import static cn.iocoder.yudao.framework.apilog.core.enums.OperateTypeEnum.EXPORT;
import static cn.iocoder.yudao.framework.common.pojo.CommonResult.success;
import static cn.iocoder.yudao.framework.common.util.collection.CollectionUtils.convertSet;

@Tag(name = "管理后台 - ERP 物料库存")
@RestController
@RequestMapping("/erp/stock")
@RequiredArgsConstructor
public class ErpStockController {
    private final ErpStockService stockService;
    private final ErpMaterialApi materialApi;
    private final ErpWarehouseService warehouseService;

    @GetMapping("/get")
    @Operation(summary = "获得物料库存")
    @Parameters({
            @Parameter(name = "id", description = "编号", example = "1"),
            @Parameter(name = "materialId", description = "物料编号", example = "10"),
            @Parameter(name = "warehouseId", description = "仓库编号", example = "2")
    })
    @PreAuthorize("@ss.hasPermission('erp:stock:query')")
    public CommonResult<ErpStockRespVO> getStock(@RequestParam(value = "id", required = false) Long id,
                                                 @RequestParam(value = "materialId", required = false) Long materialId,
                                                 @RequestParam(value = "warehouseId", required = false) Long warehouseId) {
        ErpStockDO stock = id != null ? stockService.getStock(id) : stockService.getStock(materialId, warehouseId);
        return success(BeanUtils.toBean(stock, ErpStockRespVO.class));
    }

    @GetMapping("/get-count")
    @Operation(summary = "获得物料库存数量")
    @Parameter(name = "materialId", description = "物料编号", example = "10")
    @Parameter(name = "warehouseId", description = "仓库编号", example = "10")
    public CommonResult<BigDecimal> getStockCount(@RequestParam(value = "warehouseId", required = false) Long warehouseId, @RequestParam("materialId") Long materialId) {
        return success(stockService.getStockCount(warehouseId, materialId));
    }

    @GetMapping("/page")
    @Operation(summary = "获得物料库存分页")
    @PreAuthorize("@ss.hasPermission('erp:stock:query')")
    public CommonResult<PageResult<ErpStockRespVO>> getStockPage(@Valid ErpStockPageReqDTO pageReqDTO) {
        PageResult<ErpStockDO> pageResult = stockService.getStockPage(pageReqDTO);
        return success(buildStockVOPageResult(pageResult));
    }

    @GetMapping("/export-excel")
    @Operation(summary = "导出物料库存 Excel")
    @PreAuthorize("@ss.hasPermission('erp:stock:export')")
    @ApiAccessLog(operateType = EXPORT)
    public void exportStockExcel(@Valid ErpStockPageReqDTO pageReqDTO,
              HttpServletResponse response) throws IOException {
        pageReqDTO.setPageSize(PageParam.PAGE_SIZE_NONE);
        List<ErpStockRespVO> list = buildStockVOPageResult(stockService.getStockPage(pageReqDTO)).getList();
        // 导出 Excel
        ExcelUtils.write(response, "物料库存.xls", "数据", ErpStockRespVO.class, list);
    }

    private PageResult<ErpStockRespVO> buildStockVOPageResult(PageResult<ErpStockDO> pageResult) {
        if (CollUtil.isEmpty(pageResult.getList())) {
            return PageResult.empty(pageResult.getTotal());
        }
        Map<Long, ErpMaterialInfoResp> materialMap = materialApi.getMaterialMap(
                convertSet(pageResult.getList(), ErpStockDO::getMaterialId));
        Map<Long, ErpWarehouseDO> warehouseMap = warehouseService.getWarehouseMap(
                convertSet(pageResult.getList(), ErpStockDO::getWarehouseId));
        return BeanUtils.toBean(pageResult, ErpStockRespVO.class, stock -> {
            MapUtils.findAndThen(materialMap, stock.getMaterialId(), product -> stock.setMaterialName(product.getName())
                    .setCategoryName(product.getCategoryName()).setUnitName(product.getUnitName()));
            MapUtils.findAndThen(warehouseMap, stock.getWarehouseId(), warehouse -> stock.setWarehouseName(warehouse.getName()));
        });
    }

}